package ai.plantdata.config;

import ai.plantdata.constant.DbTypeEnum;
import ai.plantdata.vo.DataSourceConfig;
import lombok.SneakyThrows;
import org.springframework.boot.jdbc.DataSourceBuilder;
import org.springframework.jdbc.datasource.DriverManagerDataSource;
import org.springframework.util.StringUtils;

import javax.sql.DataSource;
import java.sql.SQLException;
import java.util.function.BiFunction;

public class RDBTemplateFactory {

    private static final BiFunction<DataSourceConfig, ConnectionDTO, DataSource> dataSourceFunction = (dbInfo, connInfo) -> {
        String dbName = dbInfo.getDbName() == null ? "" : dbInfo.getDbName();
        String url;
        if (!StringUtils.isEmpty(dbInfo.getUrl())) {
            url = dbInfo.getUrl();
        } else {
            url = connInfo.getUrlFactory().apply(dbInfo.getAddress(), dbName);
        }
        return DataSourceBuilder
                .create()
                .url(url)
                .type(DriverManagerDataSource.class)
                .password(dbInfo.getPassWord())
                .username(dbInfo.getUserName())
                .driverClassName(connInfo.getDriverClass())
                .build();
    };

    @SneakyThrows(SQLException.class)
    public static DataSource factory(DataSourceConfig dbInfo, DbTypeEnum dbType) {

        final ConnectionDTO connInfo;
        switch (dbType) {
            case MYSQL:
                connInfo = ConnectionDTO.MYSQL;
                break;
            case ORACLE:
                connInfo = ConnectionDTO.ORACLE;
                break;
            default:
                throw new SQLException("暂不支持");
        }
        return dataSourceFunction.apply(dbInfo, connInfo);
    }


}